package com.example.sfm.config;

import com.example.sfm.interceptor.JwtTokenAdminInterceptor;
import com.example.sfm.interceptor.JwtTokenUserInterceptor;
import com.example.sfm.json.JacksonObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

@Configuration
@Slf4j
@RequiredArgsConstructor
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    private final JwtTokenAdminInterceptor adminInterceptor;
    private final JwtTokenUserInterceptor userInterceptor;

    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        log.info("开始注册拦截器:{}", registry);
        registry.addInterceptor(adminInterceptor)
                .addPathPatterns("/admin/**", "/common/admin/**")
                .excludePathPatterns("/admin/login", "/captcha/**", "/swagger-ui/**",
                        "/v3/api-docs/**", "/doc.html", "/swagger-resources/**");

        registry.addInterceptor(userInterceptor)
                .addPathPatterns("/user/**", "/common/user/**")
                .excludePathPatterns("/user/user/login", "/user/user/register",
                        "/captcha/**", "/swagger-ui/**", "/v3/api-docs/**", "/doc.html", "/swagger-resources/**");
    }


    /**
     * 扩展spring mvc框架的消息转化器
     */
    @Override
    protected void extendMessageConverters(@NotNull List<HttpMessageConverter<?>> converters) {
        //创建一个消息转换器
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).findFirst()
                .ifPresent(c -> ((MappingJackson2HttpMessageConverter) c).setObjectMapper(new JacksonObjectMapper()));
    }


    /**
     * 设置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
